<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="username" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">手机号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="mobile" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select name="status">
                                    <option value="">全部</option>
                                    <option value="1">启用</option>
                                    <option value="2">禁用</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="user-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>
        <table class="layui-hide" id="userTable" lay-filter="userTableFilter"></table>
        <script type="text/html" id="userTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
        <!-- 编辑/添加弹窗 -->
        <div id="editUser" style="display: none">
            <div class="layui-form layuimini-form" lay-filter="editUserForm">
                <div class="layui-form-item" id="userId-laylabel">
                    <label class="layui-form-label">用户ID</label>
                    <div class="layui-input-inline">
                        <input type="text" name="userId" placeholder="自动生成" readonly value="" class="layui-input layui-disabled">
                    </div>
                </div>
                <div class="layui-form-item" id="username-laylabel">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="username" placeholder="请输入用户名" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" id="password-laylabel">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="password" placeholder="请输入密码（编辑时可留空）" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" id="roleId-laylabel">
                    <label class="layui-form-label required">角色</label>
                    <div class="layui-input-inline">
                        <select name="roleId" id="roleSelect" lay-verify="required" lay-reqtext="角色不能为空">
                            <option value="">请选择角色</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item" id="realName-laylabel">
                    <label class="layui-form-label">真实姓名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="realName" placeholder="请输入真实姓名" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="mobile" placeholder="请输入手机号" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">邮箱</label>
                    <div class="layui-input-inline">
                        <input type="email" name="email" lay-verify="required|email" lay-reqtext="邮箱不能为空" placeholder="请输入邮箱" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">状态</label>
                    <div class="layui-input-inline">
                        <select name="status" lay-verify="required">
                            <option value="1">启用</option>
                            <option value="2">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveUserBtn">确认保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        // 全局设置ajax请求头
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                //输出token
                console.log(data.token);
                if (data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });
        // 直接加载角色数据
        loadRoleData();

        table.render({
            elem: '#userTable',
            url: '/user/query',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'userId', width: 80, title: 'ID', sort: true},
                {field: 'username', width: 120, title: '用户名'},
                {field: 'roleId', width: 120, title: '角色', templet: function(d){ 
                    return roleDataCache[d.roleId] || d.roleId || '';
                }},
                {field: 'realName', width: 100, title: '真实姓名'},
                {field: 'mobile', width: 120, title: '手机号'},
                {field: 'status', width: 80, title: '状态', templet: function(d){ return d.status==1?'启用':'禁用';}},
                {field: 'email', width: 160, title: '邮箱'},
                {title: '操作', minWidth: 200, toolbar: '#userTableBar', align: "center",fixed: 'right'}
            ]],
            limits: [5, 10, 20, 50],
            limit: 10,
            page: true,
            skin: 'line',
        });

        // 监听搜索操作
        form.on('submit(user-search-btn)', function (data) {
            table.reload('userTable', {
                page: { curr: 1 },
                where: data.field
            });
            return false;
        });
        const userStr = localStorage.getItem('user');
        // 转换为 JS 对象
        const user = JSON.parse(userStr);
        
        // 角色数据缓存
        var roleDataCache = {};
        
        // 加载角色数据
        function loadRoleData(callback) {
            $.get('/role/list', function(res) {
                if (res.code === 0 && res.data && res.data.length > 0) {
                    var options = '<option value="">请选择角色</option>';
                    res.data.forEach(function(role) {
                        options += '<option value="' + role.roleId + '">' + role.roleName + '</option>';
                        // 缓存角色数据用于表格显示
                        roleDataCache[role.roleId] = role.roleName;
                    });
                    $('#roleSelect').html(options);
                    form.render('select'); // 重新渲染select
                    
                    // 如果有回调函数，执行回调
                    if (callback && typeof callback === 'function') {
                        callback();
                    }
                } else {
                    layer.msg('加载角色数据失败');
                }
            }).fail(function() {
                layer.msg('加载角色数据失败');
            });
        }
        
        // 工具栏监听 - 添加
        table.on('toolbar(userTableFilter)', function (obj) {
            if (obj.event === 'add') {
                // 先加载角色数据，然后打开弹窗
                loadRoleData(function() {
                    // 显示需要显示的字段（如 ID、密码等）
                    $("#userId-laylabel,#password-laylabel,#roleId-laylabel,#realName-laylabel").show();

                    // 清空表单数据
                    form.val("editUserForm", {
                        userId: '',       // 自动填充的ID清空
                        username: '',     // 用户名
                        password: '',     // 密码
                        roleId: '',       // 角色ID
                        realName: '',     // 真实姓名
                        mobile: '',       // 手机号
                        email: '',        // 邮箱
                        status: '1'       // 默认启用状态
                    });

                    // 打开弹窗
                    index = layer.open({
                        title: '添加用户',
                        type: 1,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['500px', '550px'],
                        content: $("#editUser")
                    });
                });
            }
        });


        // 行内按钮监听 - 编辑/删除/启用/禁用
        table.on('tool(userTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                // 先加载角色数据，然后打开弹窗
                loadRoleData(function() {
                    $("#userId-laylabel,#password-laylabel,#realName-laylabel").hide();
                    form.val("editUserForm", data);
                    index = layer.open({
                        title: '编辑用户',
                        type: 1,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['500px', '550px'],
                        content: $("#editUser")
                    });
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除该用户？该用户所创建的所有信息都会被删除！！', function (index) {
                    $.post("/user/delete", {userId: data.userId}, function (res) {
                        if (res.code === 0) {
                            layer.msg("删除成功");
                            obj.del();
                        } else {
                            layer.msg(res.msg || "删除失败");
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'disable') {
                $.post('/user/status', {userId: data.userId, status: 2}, function(res){
                    if(res.code === 0){
                        layer.msg('禁用成功');
                        table.reload('userTable');
                    }else{
                        layer.msg(res.msg || '禁用失败');
                    }
                });
            } else if (obj.event === 'enable') {
                $.post('/user/status', {userId: data.userId, status: 1}, function(res){
                    if(res.code === 0){
                        layer.msg('启用成功');
                        table.reload('userTable');
                    }else{
                        layer.msg(res.msg || '启用失败');
                    }
                });
            }
        });

        // 表单提交监听
        form.on('submit(saveUserBtn)', function (data) {
            var field = data.field;
            var url = field.userId ? "/user/update" : "/user/add";
            
            // 自动设置默认头像地址
            field.avatar = '/images/default_avatar.png';
            
            $.post(url, field, function (res) {
                if (res.code === 0) {
                    layer.msg(field.userId ? "更新成功" : "添加成功");
                    layer.closeAll();
                    table.reload('userTable');
                } else {
                    layer.msg(field.userId ? "更新失败" : "添加失败");
                }
            });
            return false;
        });
    });
</script>
</body>
</html> 